package com.example.demo.ykj.counts;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjq
 * @version 创建时间：2022-06-08 15:24:52
 */

@Api(tags = {"余康俊的数据"})
@RestController
@RequestMapping("/ykj")
public class CountsController {

    @Autowired
    private CountsService testService;
    //最简单的读取，excel中的数据列需要跟实体类一一对应
    @ApiOperation(value = "写入数据库")
    @PostMapping("upload1")
    @ResponseBody
    public void upload1(MultipartFile file) throws IOException {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(file.getInputStream(), Counts.class, new PageReadListener<Counts>(dataList -> {
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            for (Counts demoData : dataList) {
                System.out.println("读取到一条数据{}" + JSON.toJSONString(demoData));
                countsRepository.save(demoData);
            }
        })).sheet().doRead();
    }

    //导出处理之后的excel
    @Autowired
    private CountsRepository countsRepository;
    @ApiOperation(value = "读出数据，写入excel")
    @GetMapping("downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        List<ExportData> list = new ArrayList<ExportData>();
        //这里可以插入一些默认数据
        List<Map<String, Object>> a = countsRepository.getStudent();
        for (int i = 0; i < a.size(); i++) {
            ExportData b = new ExportData();
            b.setSuid(a.get(i).get("suid") + "");
            b.setHuji(a.get(i).get("huji") + "");
            b.setJjjz(a.get(i).get("jjjz") + "");
            list.add(b);
        }

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ExportData.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    //此方法手动导入本地路径下的数据，自己指定文件的参照BaseUserController
    @ApiOperation(value = "最简单的读（写入数据库）---弃用")
    @PostMapping("/model/du")
    public void exportTemplate() {
        testService.importTemplates();
    }

    @ApiOperation(value = "最简单的读（写入数据库），使用监听器----弃用")
    @PostMapping("/model/dus")
    public void exportTemplate2() {
        testService.importTemplatess();
    }
}